package initconf

import (
	"fmt"
	viewmodel "go_stu_gin/view_model"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func InitMysql(config *viewmodel.InitConfig) (*gorm.DB, error) {
	dsn := "%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local"
	dsn = fmt.Sprintf(dsn, config.Mysql.User, config.Mysql.PassWord, config.Mysql.Host, config.Mysql.Port, config.Mysql.DbName)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return nil, err
	}
	// 打印出对应的sql
	if config.Base.Env == "dev" {
		db.Logger = logger.Default.LogMode(logger.Info)
	}

	return db, nil
}
